{% extends 'index.html' %}
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<style type="text/css">
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }	
</style>
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa fa-gears"></i><code>MySQL</code>管理</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
 						<i class="fa    fa-gears"></i>SQL执行
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-4">
                                <legend><i class="fa  fa-paper-plane"></i>MySQL服务器</legend>
                                    <form  method="post" id="dbOps">  {% csrf_token %}
										<div class="form-group" >			 		             
											<label >环境类型</label>	
											<select class="form-control"  name="ops_env" id="ops_env" onchange="javascript:oBtEnvSelect();">
												<option name="ops_env" value="" selected="selected">选择一个类型操作</option>
												<option name="ops_env" value="test" >测试</option>
												<option name="ops_env" value="prod" >生产</option>
											</select>		
										</div>  
										<div class="form-group" >			 		             
											<label >所属产品线</label>	
											<select class="form-control"  name="ops_project" id="ops_project" onchange="javascript:oBtProjectSelect();">
												<option name="ops_project" value="" selected="selected">选择一个产品线</option>
												{% for ds in projectList %}
													<option value="{{ds.id}}" name="ops_project">{{ds.project_name}}</option>
												{% endfor %}
											</select>		
										</div> 
										<div class="form-group">
											<label >业务类型</label>
											<select class="form-control" name="ops_service" id="ops_service" onchange="javascript:oBtServiceSelect();">
												   <option selected="selected" value="">请选择一个类型</option>								   							
											</select>
										</div>										                                   	 
<!-- 										<div class="form-group" >			 		             
											<label >业务类型</label>	
											<select class="form-control"  name="ops_service" id="ops_service" onchange="javascript:oBtServiceSelect();">
												<option name="ops_service" value="" selected="selected">选择一个业务操作</option>
												{% for ds in serviceList %}
													<option value="{{ds.id}}" name="ops_service">{{ds.service_name}}</option>
												{% endfor %}
											</select>		
										</div>  -->                                   
										<div class="form-group" >			 		             
											<label >数据库</label>	
											<select class="form-control"  name="ops_db" id="ops_db" onchange="javascript:oBtDbsSelect();">
												<option name="ops_db" value="" selected="selected">选择一个数据库操作</option>
											</select>		
										</div>
																				
										<div id="service_server" class="form-group">
											<label >操作类型</label>
		                                    <select class="form-control" name="ops_tag"  id="ops_tag" onchange="javascript:oBtDbsOps();">
		                                    		<option name="ops_tag" value="" selected="selected">选择一个类型操作</option>
		                                    		<option name="ops_tag" value="1">DML回滚语句</option>
		                                            <option name="ops_tag" value="2">SQL优化建议</option>
		                                            <option name="ops_tag" value="3">执行DQL语句</option>
		                                            {% if  user.is_superuser %}
		                                            <option name="ops_tag" value="4">执行原生SQL语句</option>
		                                            {% endif %}
	                                    	</select>
										</div>												
										<div id="div_ops_binlog" style="display:none;">
											<div  class="form-group">
												<label>选择binlog</label>
			                                    <select class="form-control" name="ops_binlog"  id="ops_binlog">
			                                    </select>
											</div>	
											<div  class="form-group">
												<label>start-datetime</label>
			                                    <input  type="text"  name="ops_startime" id="ops_startime" class="form-control form_datetime" data-date-format="yyyy-mm-dd hh:ii" title="例如2016-01-01" required>
			                                    </select>
											</div>	
											<div  class="form-group">
												<label>end-datetime</label>
			                                    <input  type="text"  name="ops_endtime"  id="ops_endtime" class="form-control form_datetime" data-date-format="yyyy-mm-dd hh:ii" title="例如2016-01-01" required>
			                                    </select>
											</div>																																		
										</div>			
										<div class="form-group" id="div_ace_editor"  style="display:none;">
											<label>SQL内容<i class="fa fa-info-circle" data-toggle="tooltip" title="输入SQL内容"></i></label>		
											<div id="compile-editor" class="ace_editor">{{order.order_sql}}</div>
											<p class="help-block">例如：insert into tablename (xxx,xxx,xxx) values (xxx,xxx,xxx);</p>									
										</div>																																									
										<br>                          											                  
                                        <button type="button" class="btn btn-default" onclick="runDbOps(this)">执行</button>	
                                        <button style="display:none;" type="button" class="btn btn-default" id="dumpsQueryData" onclick="fcDumpsQueryData(this)">导出</button>		                                   
		                                                               	
                                </div>                            
                                <div class="col-lg-8">
                                    <legend><i class="fa  fa-paper-plane-o"></i>执行结果</legend>
									<pre>
				                        <div id="result">
				                        </div>
				                    </pre>                                      
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
</div>

<script type="text/javascript">
	$(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
	function setAceEditMode(model) {
		var editor = ace.edit("compile-editor");
		require("ace/ext/old_ie");
		var langTools = ace.require("ace/ext/language_tools");
		editor.removeLines();
		editor.setTheme("ace/theme/monokai");
		editor.getSession().setMode("ace/mode/" + model);
		editor.setShowPrintMargin(false);
		editor.setOptions({
		    enableBasicAutocompletion: true,
		    enableSnippets: true,
		    enableLiveAutocompletion: true
		}); 
				 
	};
	
	setAceEditMode("mysql");
	function oBtEnvSelect(){
		$('#ops_binlog option:selected').empty();
		$('#ops_db option:selected').empty();
		$("#ops_service").val("");
		document.getElementById("dumpsQueryData").style.display = "none";
	}
 	function oBtServiceSelect(){		
		var service = $('#ops_service option:selected').val();
		var env = $('#ops_env option:selected').val();	
		document.getElementById("dumpsQueryData").style.display = "none";
		if (service >= 1){
			$.ajax({
				dataType: "JSON",
				url:'/db/sql/ops/', //请求地址
				type:"POST",  //提交类似
				data:{
					'model':'querydb',
					'db_service':service,
					'db_env':env,
				},  //提交参数
				success:function(response){
					var dbHtml = '<select class="form-control"  name="ops_db" id="ops_db" onchange="javascript:oBtDbsSelect();"><option name="ops_db" value="" selected="selected">选择一个数据库进行操作</option>'
					var selectHtml = '';
					for (var i=0; i <response["data"].length; i++){
						 selectHtml += '<option name="ops_db" value="'+ response["data"][i]['id'] +'">' + response["data"][i]['db_name'] +  '(' + response["data"][i]['db_host'] + ')' + '</option>' 
					};                        
					dbHtml =  dbHtml + selectHtml + '</select>';
					document.getElementById("ops_db").innerHTML= dbHtml;
					$('#ops_binlog option:selected').empty();
						
				},
			});			   	
		}
	}
	
	function oBtProjectSelect(){
		   $('#ops_service').removeAttr("disabled");
		   var obj = document.getElementById("ops_project"); 
		   var index = obj.selectedIndex;
		   var projectId = obj.options[index].value; 
		   if ( projectId > 0){	 
				$.ajax({
					dataType: "JSON",
					url:'/api/project/'+ projectId + '/', //请求地址
					type:"GET",  //提交类似
					success:function(response){
						var binlogHtml = '<select class="form-control" name="ops_service" id="ops_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="ops_service" value="">请选择业务类型</option>'
						var selectHtml = '';
						for (var i=0; i <response["service_assets"].length; i++){
							 selectHtml += '<option name="ops_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
						};                        
						binlogHtml =  binlogHtml + selectHtml + '</select>';
						document.getElementById("ops_service").innerHTML= binlogHtml;	
							
					},
				});	
		   }
		   else{
			   $('#ops_service').attr("disabled",true);
		   }

	}
	
	
	function oBtDbsOps(){
		   var obj = document.getElementById("ops_tag"); 
		   var index = obj.selectedIndex;
		   var value = obj.options[index].value; 
		   document.getElementById("dumpsQueryData").style.display = "none";
		   if (value >= 2){
			   document.getElementById("div_ace_editor").style.display = "";
			   document.getElementById("div_ops_binlog").style.display = "none";
		   }
		   else if (value == 1){
			   document.getElementById("div_ace_editor").style.display = "none";
			   document.getElementById("div_ops_binlog").style.display = "";
			   var dbId = $('#ops_db option:selected').val();	
			   if ( dbId.length > 0){	 
					$.ajax({
						dataType: "JSON",
						url:'/db/sql/ops/', //请求地址
						type:"POST",  //提交类似
						data:{
							'model':'binlog',
							'ops_db':dbId
						},  //提交参数
						success:function(response){
							var binlogHtml = '<select class="form-control" name="ops_binlog"  id="ops_binlog">'
							var selectHtml = '';
							for (var i=0; i <response["data"].length; i++){
								 selectHtml += '<option name="ops_binlog" value="'+ response["data"][i] +'">' + response["data"][i] + '</option>' 
							};                        
							binlogHtml =  binlogHtml + selectHtml + '</select>';
							document.getElementById("ops_binlog").innerHTML= binlogHtml;		
						},
					});	
			   };		   
		   }
		   else {
			   document.getElementById("div_ace_editor").style.display = "none";
			   document.getElementById("div_ops_binlog").style.display = "none";
		   }	
	}

	function oBtDbsSelect(){
		   $('#ops_binlog option:selected').empty();
		   var dbId = $('#ops_db option:selected').val();
		   var opsTag = $('#ops_tag option:selected').val();
		   if ( dbId.length > 0 && opsTag == 1){	 
				$.ajax({
					dataType: "JSON",
					url:'/db/sql/ops/', //请求地址
					type:"POST",  //提交类似
					data:{
						'model':'binlog',
						'ops_db':dbId
					},  //提交参数
					success:function(response){
						var binlogHtml = '<select class="form-control" name="ops_binlog"  id="ops_binlog">'
						var selectHtml = '';
						for (var i=0; i <response["data"].length; i++){
							 selectHtml += '<option name="ops_binlog" value="'+ response["data"][i] +'">' + response["data"][i] + '</option>' 
						};                        
						binlogHtml =  binlogHtml + selectHtml + '</select>';
						document.getElementById("ops_binlog").innerHTML= binlogHtml;	
							
					},
				});	
		   };
	
	}

	function runDbOps(obj){
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		var form = document.getElementById('dbOps');
		var editor = ace.edit("compile-editor");
	    var contents = editor.getSession().getValue();
	    var dbId = $('#ops_db option:selected').val();
	    var opsTag = $('#ops_tag option:selected').val();
	    if ( contents.length == 0 && opsTag != 1 ){
	    	window.wxc.xcConfirm("SQL内容不能为空或者数据库不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	btnObj.removeAttr('disabled');
	    	return false;
	    }
	    else if(dbId.length == 0){
	    	window.wxc.xcConfirm("数据库不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	btnObj.removeAttr('disabled');
	    	return false;	    	
	    };
	    $("#result").html("服务器正在处理，请稍等。。。");
		$.ajax({
			url:'/db/sql/ops/', //请求地址
			type:"POST",  //提交类似
			data:{
				'opsTag':opsTag,
				'dbId':$('#ops_db option:selected').val(),
				'binlog':$('#ops_binlog option:selected').val(),
				'startime':document.getElementById("ops_startime").value,
				'endtime':document.getElementById("ops_endtime").value,
				'sql':contents,
			},
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response['tag'] == 1){
					var selectHtml = '<div id="result">';
					for (var i=0; i <response["data"].length; i++){
						 selectHtml +=  response["data"][i]+'<br>';
					}; 		
					selectHtml = selectHtml + '</div>';
					document.getElementById("result").innerHTML= selectHtml;
				}
				else if(response['tag'] == 2){
					var selectHtml = '<div id="result">' + response["data"] + '</div>';
					document.getElementById("result").innerHTML= selectHtml;						
				}
				else if(response['tag'] == 3){
					if (response['code'] == "200" && response['count'] > 0 ){
						var tableHtml = '<table class="table"><thead><tr>'     	
					    var trHtml = '';
						for (var i=0; i <response["data"]['colName'].length; i++){
							trHtml = trHtml + '<th>' + response["data"]['colName'][i] +'</th>';
						}; 
						tableHtml = tableHtml + trHtml + '</tr></thead><tbody>';
						var trsHtml = '';
						for (var i=0; i <response["data"]['dataList'].length; i++){
							var tdHtml = '<tr>';
							for (var x=0; x < response["data"]['dataList'][i].length; x++){
								tdHtml = tdHtml + '<td>' + response["data"]['dataList'][i][x] +'</td>';
							} 	
							trsHtml = trsHtml + tdHtml + '</tr>';
						}                    	
						tableHtml = tableHtml + trsHtml +  '</tbody></table>';
						document.getElementById("result").innerHTML= tableHtml;
						document.getElementById("dumpsQueryData").style.display = "";
					}
					else{
						var selectHtml = '<div id="result">' + response["data"] + '</div>';
						document.getElementById("result").innerHTML= selectHtml;						
					}	
				}				
				},
				
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("运行失败", window.wxc.xcConfirm.typeEnum.error);
	    	}
		})			
	};
	
	var downLoadFile = function (options) {
	    var config = $.extend(true, { method: 'post' }, options);
	    var $iframe = $('<iframe id="down-file-iframe"/>');
	    var $form = $("<form target='down-file-iframe' method=" + config.method + " />");
	    $form.attr('action', config.url);
	    for (var key in config.data) {
	    	console.log('<input type="hidden" name="' + key + '" value="' + config.data[key] +  '"/>');
	        $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] +  '"/>');
	    }
	    $form.append("{% csrf_token %}");
	    $iframe.append($form);
	    $(document.body).append($iframe);
	    $form[0].submit();
	    $iframe.remove();
	}	
	
	function fcDumpsQueryData(obj){
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
	    var url = "/db/sql/dumps/";
	    var editor = ace.edit("compile-editor");
	    var contents = editor.getSession().getValue();
	    var dbId = $('#ops_db option:selected').val();
	    var opsTag = $('#ops_tag option:selected').val();
	    if ( contents.length == 0 && opsTag != 1 ){
	    	window.wxc.xcConfirm("SQL内容不能为空或者数据库不能为空", window.wxc.xcConfirm.typeEnum.error);
	    	btnObj.removeAttr('disabled');
	    	return false;
	    };	    
        var data = {
				'dbId':$('#ops_db option:selected').val(),
				'sql':contents,
         } ;
        downLoadFile({ //调用下载方法
		        url:url,data:data
		        });
        btnObj.removeAttr('disabled');
		}
		

{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
</script>

{% endblock %}